﻿using Common.Algorithm;
using Common.LoadBalancer.Abstractions;
using Common.MefHelp;
using Common.ServiceDiscovery.Model;
using Common.Tools;

namespace Common.CustomLoadBalancer
{
    /// <summary>
    /// 最佳资源负载均衡
    /// </summary>
    public class BestResourcesSelector : ILoadBalancer
    {
        private readonly Func<Task<IList<ServiceInformation>>> _services;
        private readonly string _serviceName;
        private int _last;
        public BestResourcesSelector(Func<Task<IList<ServiceInformation>>> services, string serviceName)
        {
            _services = services;
            _serviceName = serviceName;
        }
        public async Task<HostAndPort> Lease()
        {
            var services = await _services.Invoke() ?? new List<ServiceInformation>();
            if (services == null || services.Count == 0)
                throw new Exception($"{_serviceName}没有找到实例");
            var model = await Mef.GetService<BestResources>().GetHost(services.Select(g => new IpAndPort
            {
                Port = g.HostAndPort.Port,
                Ip = g.HostAndPort.Address,
            }).ToList());
            HostAndPort result;
            if (model == null)
            {
                LogHelper.Error($"获取自定义负载均衡机器为空");
                result = services.First().HostAndPort;
            }
            else
            {
                result = services.FirstOrDefault(x =>
                x.HostAndPort.Address == model.Ip && x.HostAndPort.Port == model.Port)?.HostAndPort
                ?? new HostAndPort(model.Ip, model.Port);

            }
            return result;
        }

        public void Release(HostAndPort hostAndPort)
        {

        }
    }
}
